<template>
  <s-layout title="订单详情">
    <view class="detail-container" v-if="state.order.id">
      <uni-card>
        <template #title>
          <view class="card-header">
            <text>订单信息</text>
            <text :class="`order-status ${formatOrderStatusColor(state.order.orderStatus)}`">{{ formatOrderStatus(state.order.orderStatus) }}</text>
          </view>
        </template>
        <view class="detail-item">
          <text class="label">订单编号:</text>
          <text class="value">{{ state.order.orderCode }}</text>
        </view>
        <view class="detail-item">
          <text class="label">创建时间:</text>
          <text class="value">{{ formatDate(state.order.createTime) }}</text>
        </view>
        <view class="detail-item">
          <text class="label">产品名称:</text>
          <text class="value">{{ state.order.productName }}</text>  <!-- 需要转换 -->
        </view>
        <view class="detail-item">
          <text class="label">代理商:</text>
          <text class="value">{{ state.order.agentName }}</text> <!-- 需要转换 -->
        </view>
          <view class="detail-item">
              <text class="label">生产方:</text>
              <text class="value">{{ state.order.manufacturerName }}</text> <!-- 需要转换 -->
          </view>

      </uni-card>

      <uni-card title="详细信息" :is-shadow="false">
        <view class="detail-item"><text class="label">细胞规格:</text><text class="value">{{ state.order.cellSpecification }}</text></view>
        <view class="detail-item"><text class="label">是否拆分:</text><text class="value">{{ state.order.isSplit ? '是' : '否' }}</text></view>
        <view class="detail-item"><text class="label">袋(管)数:</text><text class="value">{{ state.order.bagCount }}</text></view>
        <view class="detail-item"><text class="label">细胞总数:</text><text class="value">{{ state.order.totalCells }}</text></view>
        <view class="detail-item"><text class="label">细胞来源:</text><text class="value">{{state.order.cellOrigin=='ALLOGENEIC'?'不指定':'自体'}}</text></view>
        <view class="detail-item"><text class="label">来源备注:</text><text class="value">{{ state.order.originRemark || '-' }}</text></view>
        <view class="detail-item"><text class="label">使用时间:</text><text class="value">{{ formatDate(state.order.usageTime) }}</text></view>
        <view class="detail-item"><text class="label">预约数量:</text><text class="value">{{ state.order.reservationQuantity }}</text></view>
          <view class="detail-item"><text class="label">订单备注:</text><text class="value">{{ state.order.remark }}</text></view>
      </uni-card>


      <uni-card title="审核与生产信息" :is-shadow="false" v-if="state.order.auditTime || state.order.productionStartTime">
        <view class="detail-item" v-if="state.order.auditTime"><text class="label">审核时间:</text><text class="value">{{ formatDate(state.order.auditTime) }}</text></view>
        <view class="detail-item" v-if="state.order.auditor"><text class="label">审核人:</text><text class="value">{{ state.order.auditorName }}</text></view>
        <view class="detail-item" v-if="state.order.rejectReason && state.order.orderStatus=='REJECTED'"><text class="label">驳回原因:</text><text class="value">{{ state.order.rejectReason }}</text></view>
        <view class="detail-item" v-if="state.order.productionStartTime"><text class="label">开始生产时间:</text><text class="value">{{ formatDate(state.order.productionStartTime) }}</text></view>
        <view class="detail-item" v-if="state.order.productionEndTime"><text class="label">完成生产时间:</text><text class="value">{{ formatDate(state.order.productionEndTime) }}</text></view>
      </uni-card>

      <uni-card title="提货信息" :is-shadow="false" v-if="state.order.pickupTime">
        <view class="detail-item"><text class="label">提货时间:</text><text class="value">{{ formatDate(state.order.pickupTime) }}</text></view>
        <view class="detail-item"><text class="label">提货备注:</text><text class="value">{{ state.order.pickupRemark || '-' }}</text></view>
        <view class="detail-item" v-if="state.order.pickupPhotos && state.order.pickupPhotos.length">
          <text class="label">提货照片:</text>
          <view class="image-list">
            <image v-for="(photo, index) in state.order.pickupPhotos" :key="index" :src="photo" mode="aspectFill" class="pickup-image" @tap="previewImage(index)"></image>
          </view>
        </view>
      </uni-card>

        <view class="audit-buttons">
        <button
                class="audit-btn ui-BG-Main-Gradient"
               v-if="state.order.orderStatus=='PENDING_PROD'"
                @click="onStartProd"
        >
            开始生产
        </button>
        <button
                class="audit-btn ui-BG-Main-Gradient"
                v-if="state.order.orderStatus=='PRODUCING'"
                @click="onFinishProd"
        >
            完成生产
        </button>
        <button
                class="audit-btn ui-BG-Main-Gradient"
                v-if="state.order.orderStatus=='PRODUCED'"
                @click="state.showModal=true"
        >
            提货
        </button>
    </view>

    </view>
    <s-empty v-else text="订单加载中..." />

      <!-- 核销完成弹出框 -->
      <CompletionModal
              v-model="state.showModal"
              :reservationData="state.order"
              @success="handleCompletionSuccess"
      />
  </s-layout>
</template>

<script setup>
  import { reactive } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import {formatDate, resetPagination} from '@/sheep/helper/utils';
  import ReservationRecordApi from '@/sheep/api/system/reservationRecord';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  import SEmpty from '@/sheep/components/s-empty/s-empty.vue';
  import UniCard from '@/uni_modules/uni-card/components/uni-card/uni-card.vue';
  import CompletionModal from "@/pages/order/components/CompletionModal.vue";

  // 订单状态枚举
  const ORDER_STATUS = {
      PENDING_REVIEW: '待审核',
      PENDING_PROD: '待生产',
      PRODUCING: '生产中',
      PRODUCED: '待提货',
      PICKED_UP: '已完成',
      REJECTED: '已驳回'
  };
  const state = reactive({
    order: {},
      showModal:false,
    orderId: null,
  });

  // 处理核销完成成功回调
  function handleCompletionSuccess() {
      // 刷新列表数据
      getOrderDetail();
  }

  const formatOrderStatus = (status) => ORDER_STATUS[status] || '未知';
  const formatOrderStatusColor = (status) => {
      const colorMap = {
          PENDING_REVIEW: 'warning-color',
          PENDING_PROD: 'warning-color',
          PRODUCING: 'primary-color', // 假设有主要颜色
          PRODUCED: 'success-color',
          PICKED_UP: 'success-color',
          REJECTED: 'danger-color'
      };
    return colorMap[status] || 'primary-color';
  };


  const onStartProd = () => {
      uni.showModal({
          title: '确认提示',
          content: '是否确认开始生产？',
          success: function (res) {
              if (res.confirm) {
                  console.log('用户确认开始生产')
                  ReservationRecordApi.startProduce(state.orderId).then(() => {
                      uni.showToast({
                          title: '操作成功',
                          icon: 'success'
                      })
                      getOrderDetail()
                  }).catch(() => {
                      uni.showToast({
                          title: '操作失败',
                          icon: 'none'
                      })
                  })
              }
          }
      })
  }

  const onFinishProd = () => {
      uni.showModal({
          title: '确认提示',
          content: '是否确认完成生产？',
          success: function (res) {
              if (res.confirm) {
                  console.log('用户确认完成生产')
                  // 调用后端接口，更新订单状态
                  ReservationRecordApi.completeProduce(state.orderId).then(() => {
                      uni.showToast({
                          title: '操作成功',
                          icon: 'success'
                      })
                      getOrderDetail()
                  }).catch(() => {
                      uni.showToast({
                          title: '操作失败',
                          icon: 'none'
                      })
                  })
              }
          }
      })
  }

  async function getOrderDetail() {
    try {
      const { code, data } = await ReservationRecordApi.getDetail({id:state.orderId});
      if (code === 0) {
        state.order = data;
      } else {
        sheep.$helper.toast('获取订单详情失败');
      }
    } catch (e) {
      console.error(e);
    }
  }


  const previewImage = (index) => {
    uni.previewImage({ urls: state.order.pickupPhotos, current: index });
  };

  onLoad((options) => {
    if (options.id) {
      state.orderId = options.id;
      getOrderDetail();
    }
  });
</script>

<style lang="scss" scoped>
  .detail-container { padding: 0rpx;  padding-bottom: 120rpx;}
  .card-header { display: flex; justify-content: space-between;
    padding-top: 20rpx;
    align-items: center; font-size: 30rpx; font-weight: 500; }
  .order-status { font-size: 26rpx; font-weight: normal; }
  .detail-item { display: flex; justify-content: space-between; padding: 20rpx 0; font-size: 28rpx; border-bottom: 1rpx solid #f5f5f5;
    .label { color: #666; }
    .value { color: #333; text-align: right; }
  }
  .detail-item:last-child { border-bottom: none; }
  .image-list { display: flex; flex-wrap: wrap; margin-top: 10rpx; justify-content: flex-end; }
  .pickup-image { width: 120rpx; height: 120rpx; margin-left: 10rpx; margin-bottom: 10rpx; border-radius: 8rpx; }
  .action-btn { width: 90%; height: 80rpx; border-radius: 40rpx; font-size: 30rpx; background-color: #f0f0f0; color: #333; }

  .warning-color { color: #faad14; }
  .danger-color { color: #ff3000; }
  .info-color { color: #999999; }
  .primary-color { color: #007aff; }
  .audit-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    gap: 20rpx;
    padding: 20rpx 20rpx;
    justify-content: center;
    background: #fff;
    z-index: 99;
    box-shadow: 0 -4rpx 8rpx rgba(0,0,0,0.05);
  }
  .audit-btn{
    width: 100%;
  }
</style>

